package com.sls.mall.authserver.controller;

import cn.hutool.Hutool;

import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.TypeReference;
import com.sls.mall.authserver.feign.MemberFeignService;
import com.sls.mall.authserver.feign.ThirdPartFeignService;
import com.sls.mall.authserver.vo.UserLoginVO;

import com.sls.mall.authserver.vo.UserRegistVO;
import com.sls.mall.common.constant.AuthServerConstant;
import com.sls.mall.common.exception.SLSCodeEnume;
import com.sls.mall.common.utils.R;
import com.sls.mall.common.vo.MemberRespVO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.session.Session;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import javax.validation.constraints.NotEmpty;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;


/**
 * @author lixue
 * @Title: LoginController
 * @ProjectName sls_mall2021
 * @Description: TODO
 * @date 2021/5/614:59
 */
@Controller
public class LoginController {

    @Autowired
    ThirdPartFeignService thirdPartFeignService;

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Autowired
    MemberFeignService memberFeignService;

    @RequestMapping("/login.html")
    public String index()
    {
        return "login";
    }

    @RequestMapping("/reg")
    public String reg()
    {
        return "reg";
    }

    @ResponseBody
    @RequestMapping("/sms/sendcode")
    public R sendCode(@RequestParam("phone")String phone)
    {

        //TODO 接口防刷

        String redisCode = stringRedisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX+phone);
        if (StringUtils.isNotEmpty(redisCode)) {
            long l = Long.parseLong(redisCode.split("_")[1]);
            if (System.currentTimeMillis() - l < 60000) {
                return R.error(SLSCodeEnume.SMS_CODE_EXCEPTION.getCode(), SLSCodeEnume.SMS_CODE_EXCEPTION.getMessage());
            }
        }

        String code = RandomUtil.randomInt(10000,99999)+"";
        String rediscode = code + "_"+System.currentTimeMillis();
        stringRedisTemplate.opsForValue().set(AuthServerConstant.SMS_CODE_CACHE_PREFIX+phone,rediscode,10L, TimeUnit.MINUTES);

        System.out.println("验证码为："+code);
        thirdPartFeignService.sendCode(phone,code);

        return R.ok();
    }









    @PostMapping("/regist")
    public String regist(@Valid UserRegistVO vo, BindingResult result, RedirectAttributes redirectAttributes)
    {

        if (result.hasErrors()) {

            //  stream 编码方式一

//            Map<String, String> collect = result.getFieldErrors().stream().collect(Collectors.toMap(fieldError -> {
//
//                return fieldError.getField();
//            }, fieldError -> {
//                return fieldError.getDefaultMessage();
//            }));


            //  stream 编码方式二

            Map<String, String> errors = result.getFieldErrors().stream().collect(Collectors.toMap(
                    FieldError::getField,
                    FieldError::getDefaultMessage,

                    // 没有这一句 会报错
                    (entity1,entity2) -> entity1
                    ));


//            model.addAttribute("errors", collect);
              redirectAttributes.addFlashAttribute("errors",errors);

            // 效验出错，转发到注册页

            //  问题一：此处为 post 请求 但是转发 /reg.html (路径映射默认都是get方式访问) 所以报错
            //  解决：转发 改为直接渲染 reg 页面

//            return "forward:/reg.html";

            //问题二： 为防止 表单重复提交 需要使用转发  但是转发无法携带数据！
            //解决： 弃用 model.addAttribute("errors", collect);  改用  redirectAttributes.addFlashAttribute("errors",collect);

//            return "reg";

            // 问题三：表单转到了 ip  没有转到域名
            // 解决：全部使用 完整地址转发
//            return "redirect:/reg.html";

            return "redirect:http://auth.malltest.com/reg.html";
        }

        //调用远程服务正真注册
        String code = vo.getCode();

        String s = stringRedisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + vo.getPhone());

        if (StringUtils.isNotEmpty(s))
        {
            if (code.equals(s.split("_")[0]))
            {
                // 删除验证码 令牌机制
                stringRedisTemplate.delete(AuthServerConstant.SMS_CODE_CACHE_PREFIX+vo.getPhone());
                //验证码通过， 调用远程服务注册
                R regist = memberFeignService.regist(vo);
                if (regist.getCode() == 0)
                {
                    // 注册成功回到首页，回到登录页
                    return "redirect:/login.html";

                }else {
                    Map<String,Object> errors = new HashMap<>();
                    errors.put("msg",regist.getData("msg",new TypeReference<String>(){}));
                    redirectAttributes.addFlashAttribute("errors",errors);

                    return "redirect:http://auth.malltest.com/reg.html";
                }
            }else {

                Map<String,Object> errors = new HashMap<>();
                errors.put("code","验证码错误");
                redirectAttributes.addFlashAttribute("errors",errors);

                return "redirect:http://auth.malltest.com/reg.html";
            }
        }else {

            Map<String,Object> errors = new HashMap<>();
            errors.put("code","验证码错误");
            redirectAttributes.addFlashAttribute("errors",errors);

            return "redirect:http://auth.malltest.com/reg.html";
        }


        // 注册成功回到首页，回到登录页
//        return "redirect:http://auth.malltest.com/login.html";

    }


    @PostMapping("/login")
    public String login(UserLoginVO loginVO, RedirectAttributes redirectAttributes,HttpSession session)
    {

        R login = memberFeignService.login(loginVO);

        if (login.getCode() == 0)
        {

           session.setAttribute(AuthServerConstant.LOGIN_USER,login.getData("data",new TypeReference<MemberRespVO>(){}));

            return "redirect:http://www.malltest.com";
        }else
        {
            Map<String, Object> errors = new HashMap<>();

            errors.put("msg",login.getData("mag",new TypeReference<String>(){}));

            redirectAttributes.addFlashAttribute("errors",errors);

            return "redirect:http://auth.malltest.com/login.html";

        }
    }


}


